<?php
/**
 * WebSocket服务
 *
 * @author		黑冰 <954650386@qq.com>
 */

namespace waf\server;

use \waf\Waf;
use \waf\log\WLog;
use \waf\server\BaseServer;
use \Yaf;

class WebSocketServer extends BaseServer
{
    public function init()
    {
        WLog::logSystem("in", __FILE__, __LINE__, __FUNCTION__);
        $this->strServerType = 'websocket';
        parent::init();
        WLog::logSystem("out", __FILE__, __LINE__, __FUNCTION__);
    }

    public function onMessage($objSServer, $objFrame)
    {
        WLog::logInfo("in:".WLog::toJson($objFrame), __FILE__, __LINE__, __FUNCTION__);
        // text
        if($objFrame->opcode == 1)
        {
            if($objFrame->finish && $objFrame->data)
            {
                $ret = $this->route($objFrame->data);
                if($ret['r'] === 0 && $ret['data'])
                {
                    try {
                        ob_start();

                        $requestObj = new \Yaf_Request_Http($ret['data']['url']);
                        $this->setParams($requestObj, $ret['data']);
                        $this->objYaf->getDispatcher()->dispatch($requestObj);

                        $result = ob_get_contents();
                        ob_end_clean();

                        $objSServer->push($objFrame->fd, $result);
                    } catch (\Throwable $e) {
                        WLog::logError("yaf_exception:".WLog::toJson(print_r($e, true)), __FILE__, __LINE__, __FUNCTION__);
                    }
                }else{
                    WLog::logError("route data exception. receive_data = ".$objFrame->data, __FILE__, __LINE__, __FUNCTION__);
                }
            }else{
                WLog::logError("data not finish", __FILE__, __LINE__, __FUNCTION__);
            }
        }else{
            WLog::logError("protocol not open", __FILE__, __LINE__, __FUNCTION__);
        }
    }
}
?>